package com.qf.dao.impl;

import com.qf.dao.UserDao;
import com.qf.domain.User;
import com.qf.utils.DataSourceUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;

import java.sql.Connection;
import java.sql.SQLException;

public class UserDaoImpl implements UserDao {
    private QueryRunner qr=new QueryRunner();
    //添加
    @Override
    public void insert(User user) {
        String sql="insert into tb_user(username,password,email,gender,flag,role,code)values(?,?,?,?,?,?,?)";
        Object[] params={user.getUsername(),user.getPassword(),user.getEmail(),user.getEmail(),user.getFlag(),user.getRole(),user.getCode()};
        Connection conn = DataSourceUtils.getConnection();
        try {
            qr.update(conn,sql,params);
        } catch (SQLException throwables) {
            throwables.printStackTrace();
            throw new RuntimeException(throwables);
        }finally {
            DataSourceUtils.closeAll(null,null,conn);
        }
    }
    //根据账户密码查询用户
    @Override
    public User select(String username, String password) {
        String sql="select id,username,password,email,gender,flag,role,code from tb_user where username=? and password=?";
        Connection conn=DataSourceUtils.getConnection();
        try {
            return qr.query(conn,sql,new BeanHandler<>(User.class),username,password);
        } catch (SQLException throwables) {
            throwables.printStackTrace();
            throw new RuntimeException("根据账户密码查询用户错误",throwables);
        }finally {
            DataSourceUtils.closeAll(null,null,conn);
        }

    }
    //查询用户是否存在
    @Override
    public boolean select(String username) {
        String sql="select id,username,password,email,gender,flag,role,code from tb_user where username=? ";
        Connection conn=DataSourceUtils.getConnection();
        try {
            User query = qr.query(conn,sql, new BeanHandler<>(User.class), username);
            if (query==null){
                return false;
            }
            return true;
        } catch (SQLException throwables) {
            throwables.printStackTrace();
            throw new RuntimeException(throwables);
        }finally {
            DataSourceUtils.closeAll(null,null,conn);
        }

    }
}
